package com.threadPool.thread;

import com.threadPool.pool.BaseThreadPool;
import com.threadPool.pool.DynamicThreadPoolManager;
import com.threadPool.pool.MyThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.TimeUnit;

public class WorkerThread extends Thread{
    private static final Logger logger = LoggerFactory.getLogger(WorkerThread.class);
    private long timeOut;
    private TimeUnit timeOutUnit;
    private BlockingDeque<Runnable> taskQueue;
    private volatile boolean isStopped = false;

    public WorkerThread(BlockingDeque<Runnable> taskQueue, long timeOut, TimeUnit timeOutUnit) {
        this.taskQueue = taskQueue;
        this.timeOut = timeOut;
        this.timeOutUnit = timeOutUnit;
    }
    public WorkerThread(){

    }

    public WorkerThread createThread(BlockingDeque<Runnable> taskQueue, long timeOut, TimeUnit timeOutUnit) {
        return new WorkerThread(taskQueue, timeOut, timeOutUnit);
    }
    public void stopThread() {
        isStopped = true;
        this.interrupt(); // 中断阻塞状态
    }
    @Override
    public void run() {
        BaseThreadPool threadPool = DynamicThreadPoolManager.getInstance().getMyThreadPool();
        Throwable thrown = null; // 新增异常变量
        while (!isStopped || !taskQueue.isEmpty()) {
            Thread currentThread = Thread.currentThread();
            Runnable task = null;
            try {
                Runnable take = taskQueue.poll(timeOut, timeOutUnit);
                if (take == null) {
                    logger.error(Thread.currentThread().getName() + " 工作线程超时,自动销毁");
                    break;
                }
                task = take;
                threadPool.beforeExecute(currentThread, task);
                take.run();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 重新设置中断状态
                thrown = e; // 记录中断异常
                break; // 退出循环
            } catch (Throwable t) { // 捕获其他异常
                thrown = t;
                // 保留原有异常处理逻辑
            } finally {
                // 调用后记录（即使发生异常）
                threadPool.afterExecute(task, thrown);
            }
        }
    }
}
